package com.kungfu.service.impl;


import com.google.gson.Gson;
import com.kungfu.config.Constant;
import com.kungfu.dao.*;
import com.kungfu.entity.*;
import com.kungfu.entity.request.*;
import com.kungfu.entity.response.CYJXInfoEntity;
import com.kungfu.entity.response.DailyQueryResponse;
import com.kungfu.entity.response.HzBean;
import com.kungfu.entity.response.MakeSureUserResponse;
import com.kungfu.service.ZzdService;
import com.kungfu.utils.DateUtils;
import com.kungfu.utils.ZzdhUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ZzdServiceImpl implements ZzdService {

    @Autowired
    private GfjsZzdMapper zzdMapper;

    @Autowired
    private ReceiptItemMapper receiptItemMapper;

    @Autowired
    private ReceiptRollsMapper receiptRollsMapper;

    @Autowired
    private ReceiptBalanceItemMapper receiptBalanceItemMapper;

    @Autowired
    private HospitalDetailTmpMapper hospitalDetailTmpMapper;

    @Autowired
    private ZzdhUtils zzdhUtils;

    @Autowired
    private DateUtils dateUtils;

    @Override
    public MakeSureUserResponse queryZzdByUserInfo(MakeSureUserRequest request) {
        //仅在住院分支使用，通过身份证号查询未生效的转诊单，如果存在，将转诊单类型修改为住院。
        Map<String, Object> result = zzdMapper.selectZzdByUserInfo(request);
        if (result != null) {
            MakeSureUserResponse response = new MakeSureUserResponse();
            int validDay = Integer.valueOf(result.get("DAYS").toString());
            Date date = (Date) result.get("CJSJ");

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE, validDay);
            date = calendar.getTime(); //这个时间就是日期往后推一天的结果
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(date);

            response.setZZYXRQ(dateString);
            response.setZGLB(result.get("ZGLB").toString());
            response.setXB(result.get("XB").toString());
            response.setDWMC(result.get("DWMC").toString());
            response.setXM(result.get("XM").toString());
            response.setZZYYMC(result.get("ZZYYMC").toString());
            response.setZZYYBH(result.get("ZZYYBH").toString());
            response.setZZDH(result.get("ZZDH").toString());
            ZzdTypeEntity entity = new ZzdTypeEntity();
            entity.setZZDH(response.getZZDH());
            entity.setZZDLX(request.getZZDLX());
            zzdMapper.updateZZDLX(entity);
            return response;
        } else {
            return null;
        }
    }

    @Override
    public int inpatientHospital(InpatientRequest request) {
        int result = zzdMapper.updateHospitalInfo(request);
        return result;
    }


    public int queryRollIsExist(Map<String, String> map) {
        return receiptRollsMapper.queryCont(map);
    }

    @Override
    public int cancelCharge(CancelChargeRequest request) {
        String jbr = request.getJBR() + "";
        request.setJBR(request.getYYBH() + jbr);
        int result = zzdMapper.updateZzdStatus(request);
        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public DataInsertResult readyToCharge(ReadyToChargeRequest request) {
        DataInsertResult insertResult = new DataInsertResult();
        if (Integer.valueOf(request.getSJDNUM()) == 0) {//当前数据条目为空 不需要插入数据
            insertResult.setResultCode(0);
            return insertResult;
        } else {
            BigDecimal totalMoney = BigDecimal.ZERO;
            int totalNum = 0;
            boolean inNeedInsert = true;
            boolean isNeedReDo = false;
            InpatientChargeTotalData reInsertData = new InpatientChargeTotalData();

            List<HospitalDetailTmpEntity> hospitalDetailTmpEntities = new ArrayList<>();
            List<ReceiptItem> list = new ArrayList<ReceiptItem>();
            if (request.getRESULTSET() != null) {
                Gson gson = new Gson();
                InpatientChargeTotalData targetItem = gson.fromJson(gson.toJson(request.getRESULTSET()), InpatientChargeTotalData.class);
                reInsertData = targetItem;
//                if (totalItem.getSJDH().equals(sjdh)) {
//                    reInsertData = totalItem;
//                    inNeedInsert = true;
//                }
                for (InpatientChargeItemData item : targetItem.getResultSet()) {
                    if ("0".equals(item.getSFJK())) {
                        //判断是否为 诊疗项目
                        item.setXMBM(item.getXMBM() + Constant.ZL_BM);
                        //这里加入 判断是否为生产手术
                        if (Constant.getOperationMap().containsKey(item.getXMBM())) {
                            zzdMapper.updateDiagnosisCode(item.getZZDH(), Constant.getOperationMap().get(item.getXMBM()));
                        }
                    }
                    if (Constant.getMxMap().containsKey(item.getXMBM())) {
                        ReceiptItem receiptItem = new ReceiptItem();
                        try {
                            receiptItem.setChargeDate(dateUtils.parseSJDH2Datetime(item.getJZSJ()));
                            Date date = dateUtils.parseSJDH2Datetime(item.getSJDH());
                            receiptItem.setReceiptNo(item.getZZDH() + dateUtils.createSJDH(date));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        receiptItem.setReceiptItemType(Constant.getDataCatalogMap().get(item.getSDML()));
                        receiptItem.setReceiptItemName(item.getXMMC());
                        receiptItem.setReceiptItemSpec(item.getYPGG());
                        receiptItem.setReceiptItemUnit(item.getDW());
                        receiptItem.setReceiptItemNum(Double.valueOf(item.getMCYL()));

                        double d1 = Double.valueOf(item.getDWFY());
                        float f1 = (float) (d1 * 100);
                        String s1 = String.valueOf(f1);
                        int dwfy = Integer.valueOf(s1.split("\\.")[0]);
                        receiptItem.setUnitFee(dwfy);//数据库单位为分

                        double d2 = Double.valueOf(item.getJE());
                        float f2 = (float) (d2 * 100);
                        String s2 = String.valueOf(f2);
                        int fee = Integer.valueOf(s2.split("\\.")[0]);

                        if (fee < 0) {
                            isNeedReDo = true;
                        }
                        receiptItem.setFee(fee);
                        receiptItem.setDetailNo(item.getXMBM());
                        receiptItem.setMajorCatalogues(Integer.valueOf(item.getSDML()));
                        receiptItem.setReceiptItemCode(item.getMXBH());
                        receiptItem.setIsImp(Constant.getYpcds().contains(item.getSFJK()) ? 1 : 0);
                        receiptItem.setStatus(0);
                        receiptItem.setBillDept(item.getKDKS());
                        receiptItem.setExeDept(item.getZXKS());
                        receiptItem.setDetailId(item.getMXBH() + item.getXMBM());
                        list.add(receiptItem);
                        //float je = Float.valueOf(item.getJE()) * 100;
                        BigDecimal je = new BigDecimal(item.getJE());
                        totalMoney = totalMoney.add(je.multiply(new BigDecimal(100)));
                        totalNum++;
                    } else {
                        HospitalDetailTmpEntity entity = new HospitalDetailTmpEntity();
                        entity.setDetailNo(item.getXMBM());
                        entity.setHospitalId(Constant.HospitalType.XH);
                        entity.setMajorCatalogues(item.getSDML());
                        double d1 = Double.valueOf(item.getDWFY());
                        float f1 = (float) (d1 * 100);
                        String s1 = String.valueOf(f1);
                        int dwfy = Integer.valueOf(s1.split("\\.")[0]);
                        entity.setDetailPrice(dwfy + "");
                        entity.setDetailName(item.getXMMC());
                        entity.setDetailXmbm(item.getMXBH());
                        entity.setCreateTime(new Date());
                        entity.setCardNo(item.getHZID());
                        entity.setUserName(item.getHZXM());
                        hospitalDetailTmpEntities.add(entity);
                    }
                }
                //
            }

            if (hospitalDetailTmpEntities.size() > 0) {
                hospitalDetailTmpMapper.insertUserData(hospitalDetailTmpEntities);
                insertResult.setResultCode(Constant.CHECK_DATA_RESULT.DATA_NOT_EXIST);
                insertResult.setRemainData(hospitalDetailTmpEntities);
                return insertResult;
            }

            //  int sjdfee = (int) (Float.valueOf(request.getSJDFEE()) * 100);
            BigDecimal sjdfee = new BigDecimal(request.getSJDFEE());
            sjdfee = sjdfee.multiply(new BigDecimal(100));
            if (totalMoney.intValue() == sjdfee.intValue() && totalNum == Integer.valueOf(request.getSJDNUM())) {
                //数据验证通过  开始插入数据库               if ()
                ReceiptRolls rolls = new ReceiptRolls();

                rolls.setUserName(request.getHZXM());
                rolls.setCardNo(request.getHZID());
                rolls.setCardId(request.getJZKH());
                try {
                    Date date = dateUtils.parseSJDH2Datetime(reInsertData.getSJDH());
                    rolls.setReceiptNo(reInsertData.getZZDH() + dateUtils.createSJDH(date));

                    rolls.setReceiptCreateTime(dateUtils.parseSJDH2Datetime(reInsertData.getSJDH()));
                    rolls.setStartDate(dateUtils.parseSJDH2Datetime(reInsertData.getSJDH()));
                    rolls.setEndDate(dateUtils.parseSJDH2Datetime(reInsertData.getSJDH()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                rolls.setIntoTime(new Date());
                rolls.setZzdNo(request.getZZDH());
                rolls.setIntoHospitalId(reInsertData.getYYBM());
                rolls.setAdmissionNumber(reInsertData.getZYH());
                rolls.setReceiptType(request.getJZLB());
                rolls.setDateNum(Integer.valueOf(1));
                rolls.setOutHospitalId("hk");
                rolls.setStatus(0);
                int rollResult = 1;
                if (inNeedInsert) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("receiptNo", rolls.getReceiptNo());
                    map.put("cardNo", rolls.getCardNo());
                    if (queryRollIsExist(map) == 0) {
                        rollResult = receiptRollsMapper.insertRoll(rolls);//插入收据表
                    } else {
                        rollResult = 1;
                    }
                }
                if (isNeedReDo) {
                    int zzdResult = zzdMapper.updateRedoFlag(request.getZZDH());
                }
                if (rollResult > 0) { //插入成功
                    int rollItemResult = receiptItemMapper.insertByList(list);
                    insertResult.setResultCode(rollItemResult);
                    return insertResult;
                }
            } else {
                insertResult.setResultCode(Constant.CHECK_DATA_RESULT.CHECK_NOT_OK);
                return insertResult; //数据未通过
            }
        }
        return insertResult;
    }

    @Override
    public DailyQueryResponse dailyChargeQuery(DailyQueryRequest request) {
        Map<String, String> result = receiptBalanceItemMapper.queryDailyCharge(request);
        DailyQueryResponse response = new DailyQueryResponse();
        if (result != null) {
            response.setFYZE(result.get("ZJE"));
            response.setGFJE(result.get("GFJE"));
            response.setZFJE(result.get("ZFJE"));
            response.setJZJLH(request.getJZJLH());
        }
        return response;
    }


    @Override
    public int cancelRegistration(CancelRegistrationRequest request) {
        return zzdMapper.cancelRegister(request);
    }

    @Override
    public GfjsZzd queryInfoByZYH(String zyh) {
        return zzdMapper.queryInfoByZYH(zyh);
    }

    @Override
    public int insertRolls(ReceiptRolls receiptRolls) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("receiptNo", receiptRolls.getReceiptNo());
        int rollResult = 0;
        map.put("cardNo", receiptRolls.getCardNo());
        if (queryRollIsExist(map) == 0) {
            rollResult = receiptRollsMapper.insertRoll(receiptRolls);//插入收据表
        }
        return rollResult;
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public DataInsertResult syncMxItem(String sjdh, String zzdh, List<MXEntity> request) {
        boolean isNeedReDo = false;
        List<ReceiptItem> list = new ArrayList<ReceiptItem>();
        List<String> existsList = receiptItemMapper.queryMXBHBySJDH(sjdh);
        List<HospitalDetailTmpEntity> hospitalDetailTmpEntities = new ArrayList<>();
        DataInsertResult dataInsertResult = new DataInsertResult();
        for (MXEntity item : request) {
            if ("0".equals(item.getYPCD())) {
                //判断是否为 诊疗项目
                item.setXMBM(item.getXMBM() + Constant.ZL_BM);
                //这里加入 判断是否为生产手术
                if (Constant.getOperationMap().containsKey(item.getXMBM())) {
                    zzdMapper.updateDiagnosisCode(item.getZZDH(), Constant.getOperationMap().get(item.getXMBM()));
                }
            }
            if (Constant.getMxMap().containsKey(item.getXMBM())) {
                ReceiptItem receiptItem = new ReceiptItem();
                try {
                    Date date = dateUtils.parseSJDH2Datetime(item.getSJDH());
                    receiptItem.setReceiptNo(zzdh + dateUtils.createSJDH(date));
                    receiptItem.setChargeDate(dateUtils.parseSJDH2Datetime(item.getJZSJ()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                receiptItem.setReceiptItemType(Constant.getDataCatalogMap().get(item.getSDML()));
                receiptItem.setReceiptItemName(item.getXMMC());
                receiptItem.setReceiptItemSpec(item.getYPGG());
                receiptItem.setReceiptItemUnit(item.getDW());
                receiptItem.setReceiptItemNum(Double.valueOf(item.getMCYL()));
                double d1 = Double.valueOf(item.getDWFY());
                float f1 = (float) (d1 * 100);
                String s1 = String.valueOf(f1);
                int dwfy = Integer.valueOf(s1.split("\\.")[0]);
                receiptItem.setUnitFee(dwfy);//数据库单位为分

                double d2 = Double.valueOf(item.getJE());
                float f2 = (float) (d2 * 100);
                String s2 = String.valueOf(f2);
                int fee = Integer.valueOf(s2.split("\\.")[0]);
                if (fee < 0) {
                    isNeedReDo = true;
                }
                receiptItem.setFee(fee);
                receiptItem.setDetailNo(item.getXMBM());
                receiptItem.setMajorCatalogues(Integer.valueOf(item.getSDML()));
                receiptItem.setReceiptItemCode(item.getMXBH());
                receiptItem.setIsImp(Constant.getYpcds().contains(item.getYPCD()) ? 1 : 0);
                receiptItem.setStatus(0);
                receiptItem.setBillDept(item.getKDKS());
                receiptItem.setExeDept(item.getZXKS());
                receiptItem.setDetailId(item.getMXBH() + item.getXMBM());
                if (!existsList.contains(item.getMXBH())) {
                    list.add(receiptItem);
                }
            } else {
                HospitalDetailTmpEntity entity = new HospitalDetailTmpEntity();
                entity.setDetailNo(item.getXMBM());
                entity.setHospitalId(Constant.HospitalType.XH);
                entity.setMajorCatalogues(item.getSDML());
                double d1 = Double.valueOf(item.getDWFY());
                float f1 = (float) (d1 * 100);
                String s1 = String.valueOf(f1);
                int dwfy = Integer.valueOf(s1.split("\\.")[0]);
                entity.setDetailPrice(dwfy + "");
                entity.setDetailName(item.getXMMC());
                entity.setDetailXmbm(item.getMXBH());
                entity.setCreateTime(new Date());
                entity.setCardNo(item.getHZID());
                entity.setUserName(item.getHZXM());
                hospitalDetailTmpEntities.add(entity);
            }
        }
        if (hospitalDetailTmpEntities.size() > 0) {
            hospitalDetailTmpMapper.insertUserData(hospitalDetailTmpEntities);
            dataInsertResult.setResultCode(Constant.CHECK_DATA_RESULT.DATA_NOT_EXIST);
            dataInsertResult.setRemainData(hospitalDetailTmpEntities);
            return dataInsertResult;
        }
        if (isNeedReDo) {
            int zzdResult = zzdMapper.updateRedoFlag(zzdh);
        }
        int rollItemResult;
        if (list.size() == 0) {
            rollItemResult = 1;
        } else {
            rollItemResult = receiptItemMapper.insertByList(list);
        }
        dataInsertResult.setResultCode(rollItemResult);
        return dataInsertResult;
    }

    @Override
    public List<HzBean> queryUnreadSum() {
        List<HzBean> list = zzdMapper.queryUnraedInfo();
        if (list.size() > 0) {
            //过滤约定数据
            list = list.stream().filter(item -> item.getZZDLX().equals("1")).filter(item -> !item.getHZRQ().contains("2000")).collect(Collectors.toList());
            list.forEach(item -> item.setHZRQ(item.getHZRQ().substring(item.getHZRQ().length() - 8, item.getHZRQ().length())));
        }

        return list;
    }

    @Override
    public int changeReadFlag(FlagChangeRequest request) {
        String hzrq = request.getHZRQ();
        request.setHZRQ(request.getZZDH() + hzrq);
        return zzdMapper.updateReadFlag(request);
    }

    @Override
    public int updateZzdInfo(InpatientChargeRequest request) {
        return zzdMapper.updateInfo(request);
    }

    @Override
    public String queryUserUnExistData(String hzid) {
        List<Map<String, String>> map = hospitalDetailTmpMapper.queryByUser(hzid);
        return new Gson().toJson(map);
    }

    @Override
    public List<CYJXInfoEntity> queryChargeList() {
        return zzdMapper.queryChargeList();
    }

    @Override
    public int queryItemCount() {
        return receiptItemMapper.queryItemCount();
    }

    @Override
    public MakeSureUserResponse queryMzZzdByUserInfo(MakeSureUserRequest request) {
        Map<String, Object> result = zzdMapper.selectZzdByUserInfo(request);
        if (result != null) {
            MakeSureUserResponse response = new MakeSureUserResponse();
            int validDay = Integer.valueOf(result.get("DAYS").toString());
            Date date = (Date) result.get("CJSJ");

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE, validDay);
            date = calendar.getTime(); //这个时间就是日期往后推一天的结果
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(date);

            response.setZZYXRQ(dateString);
            response.setZGLB(result.get("ZGLB").toString());
            response.setXB(result.get("XB").toString());
            response.setDWMC(result.get("DWMC").toString());
            response.setXM(result.get("XM").toString());
            response.setZZYYMC(result.get("ZZYYMC").toString());
            response.setZZYYBH(result.get("ZZYYBH").toString());
            response.setZZDH(result.get("ZZDH").toString());
            ZzdTypeEntity entity = new ZzdTypeEntity();
            entity.setZZDH(response.getZZDH());
            entity.setZZDLX(request.getZZDLX());
            zzdMapper.updateZZDLX(entity);
            return response;
        } else {
            return null;
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public DataInsertResult outpatientCharge(OutpatientRequest request) {
        DataInsertResult insertResult = new DataInsertResult();
        if (request.getRESULTSET() == null || request.getRESULTSET().size() == 0) {//当前数据条目为空 不需要插入数据
            insertResult.setResultCode(0);
            return insertResult;
        } else {
            BigDecimal totalMoney = BigDecimal.ZERO;
            int totalNum = 0;
            boolean inNeedInsert = true;
            boolean isNeedReDo = false;
            //    InpatientChargeTotalData reInsertData = new InpatientChargeTotalData();

            List<HospitalDetailTmpEntity> hospitalDetailTmpEntities = new ArrayList<>();
            List<ReceiptItem> list = new ArrayList<ReceiptItem>();
            if (request.getRESULTSET() != null) {
//                if (totalItem.getSJDH().equals(sjdh)) {
//                    reInsertData = totalItem;
//                    inNeedInsert = true;
//                }
                for (OutpatientItemData item : request.getRESULTSET()) {
                    if ("0".equals(item.getYPCD())) {
                        //判断是否为 诊疗项目
                        item.setXMBM(item.getXMBM() + Constant.ZL_BM);
                    }
                    if (Constant.getMxMap().containsKey(item.getXMBM())) {
                        ReceiptItem receiptItem = new ReceiptItem();
                        try {
                            Date date = dateUtils.parseSJDH2Datetime(request.getJSRQ());
                            receiptItem.setChargeDate(date);
                            receiptItem.setReceiptNo(request.getZZDH() +  item.getFPHM());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        receiptItem.setReceiptItemType(Constant.getDataCatalogMap().get(item.getSDML()));
                        receiptItem.setReceiptItemName(item.getXMMC());
                        receiptItem.setReceiptItemSpec(item.getYPGG());
                        receiptItem.setReceiptItemUnit(item.getDW());
                        receiptItem.setReceiptItemNum(Double.valueOf(item.getMCYL()));

                        double d1 = Double.valueOf(item.getDWFY());
                        float f1 = (float) (d1 * 100);
                        String s1 = String.valueOf(f1);
                        int dwfy = Integer.valueOf(s1.split("\\.")[0]);
                        receiptItem.setUnitFee(dwfy);//数据库单位为分

                        double d2 = Double.valueOf(item.getJE());
                        float f2 = (float) (d2 * 100);
                        String s2 = String.valueOf(f2);
                        int fee = Integer.valueOf(s2.split("\\.")[0]);

                        if (fee < 0) {
                            isNeedReDo = true;
                        }
                        receiptItem.setFee(fee);
                        receiptItem.setDetailNo(item.getXMBM());
                        receiptItem.setMajorCatalogues(Integer.valueOf(item.getSDML()));
                        receiptItem.setReceiptItemCode(item.getXMBH());
                        receiptItem.setIsImp(Constant.getYpcds().contains(item.getYPCD()) ? 1 : 0);
                        receiptItem.setStatus(0);
                        receiptItem.setBillDept(item.getKDKS());
                        receiptItem.setExeDept(item.getZXKS());
                        receiptItem.setDetailId(item.getXMBH() + item.getXMBM());
                        list.add(receiptItem);
                        // float je = Float.valueOf(item.getJE()) * 100;
                        BigDecimal je = new BigDecimal(item.getJE());
                        totalMoney = totalMoney.add(je.multiply(new BigDecimal(100)));
                        totalNum++;
                    } else {
                        HospitalDetailTmpEntity entity = new HospitalDetailTmpEntity();
                        entity.setDetailNo(item.getXMBM());
                        entity.setHospitalId(Constant.HospitalType.XH);
                        entity.setMajorCatalogues(item.getSDML());
                        double d1 = Double.valueOf(item.getDWFY());
                        float f1 = (float) (d1 * 100);
                        String s1 = String.valueOf(f1);
                        int dwfy = Integer.valueOf(s1.split("\\.")[0]);
                        entity.setDetailPrice(dwfy + "");
                        entity.setDetailName(item.getXMMC());
                        entity.setDetailXmbm(item.getXMBM());
                        entity.setCreateTime(new Date());
                        entity.setCardNo(request.getHZID());
                        entity.setUserName(request.getHZXM());
                        hospitalDetailTmpEntities.add(entity);
                    }
                }
                //
            }

            if (hospitalDetailTmpEntities.size() > 0) {
                hospitalDetailTmpMapper.insertUserData(hospitalDetailTmpEntities);
                insertResult.setResultCode(Constant.CHECK_DATA_RESULT.DATA_NOT_EXIST);
                insertResult.setRemainData(hospitalDetailTmpEntities);
                return insertResult;
            }

            //      int sjdfee = (int) (Float.valueOf(request.getFYZE()) * 100);
            BigDecimal sjdfee = new BigDecimal(request.getFYZE());
            sjdfee = sjdfee.multiply(new BigDecimal(100));
            if (totalMoney.intValue() == sjdfee.intValue() && totalNum == request.getRESULTSET().size()) {
                //数据验证通过  开始插入数据库               if ()
                ReceiptRolls rolls = new ReceiptRolls();

                rolls.setUserName(request.getHZXM());
                rolls.setCardNo(request.getHZID());
                rolls.setCardId(request.getJZKH());
                try {
                    Date date = dateUtils.parseSJDH2Datetime(request.getJSRQ());
                    rolls.setReceiptNo(request.getZZDH() + request.getFPHM());

                    rolls.setReceiptCreateTime(date);
                    rolls.setStartDate(date);
                    rolls.setEndDate(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                rolls.setIntoTime(new Date());
                rolls.setZzdNo(request.getZZDH());
                rolls.setIntoHospitalId(request.getYYBH());
                rolls.setAdmissionNumber(request.getJZBH());
                rolls.setReceiptType(Constant.ZzdType.MZ + "");
                rolls.setDateNum(Integer.valueOf(1));
                rolls.setOutHospitalId(request.getYYBH());
                rolls.setStatus(0);
                int rollResult = 1;
                if (inNeedInsert) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("receiptNo", rolls.getReceiptNo());
                    map.put("cardNo", rolls.getCardNo());
                    if (queryRollIsExist(map) == 0) {
                        rollResult = receiptRollsMapper.insertRoll(rolls);//插入收据表
                    } else {
                        rollResult = 1;
                    }
                }
//                if (isNeedReDo) {
//                    int zzdResult = zzdMapper.updateRedoFlag(request.getZZDH());
//                }
                if (rollResult > 0) { //插入成功
                    int rollItemResult = receiptItemMapper.insertByList(list);
                    insertResult.setResultCode(rollItemResult);
                    return insertResult;
                }
            } else {
                insertResult.setResultCode(Constant.CHECK_DATA_RESULT.CHECK_NOT_OK);
                return insertResult; //数据未通过
            }
        }
        return insertResult;
    }

    @Override
    public MakeSureUserResponse queryMXzZdBySate(MakeSureUserRequest request) {
        Map<String, Object> result = zzdMapper.selectZzdByState(request);
        if (result != null) {
            MakeSureUserResponse response = new MakeSureUserResponse();
            int validDay = Integer.valueOf(result.get("DAYS").toString());
            Date date = (Date) result.get("CJSJ");

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE, validDay);
            date = calendar.getTime(); //这个时间就是日期往后推一天的结果
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(date);

            response.setZZYXRQ(dateString);
            response.setZGLB(result.get("ZGLB").toString());
            response.setXB(result.get("XB").toString());
            response.setDWMC(result.get("DWMC").toString());
            response.setXM(result.get("XM").toString());
            response.setZZYYMC(result.get("ZZYYMC").toString());
            response.setZZYYBH(result.get("ZZYYBH").toString());
            response.setZZDH(result.get("ZZDH").toString());
            return response;
        } else {
            return null;
        }
    }

    @Override
    public int updateZZdState(String zzdh) {
        //生效门诊转诊单
        return zzdMapper.useMzZzd(zzdh);
    }

    /**
     * 查询生效的门诊转诊单
     *
     * @param sureUserRequest
     * @return
     */
    @Override
    public GfjsZzd queryUsedMzZzd(MakeSureUserRequest sureUserRequest) {
        return zzdMapper.queryUsedZZd(sureUserRequest);
    }

    @Override
    public int cancelZzd(String zzdNo) {
        //start 20190108 by chj
        //门诊转住院，对于旧的转诊单，如果有金额存在，将转诊单改为已完结，若果没有金额产生，将转诊单改为已失效。
        //查询旧转诊单是否存在金额
        GfjsZzd zzd = zzdMapper.queryZzdByZzdNo(zzdNo);
        if(null != zzd && zzd.getFee() !=0 ){
            //设置为已完结
            return zzdMapper.changeZzdStatus1(zzdNo);
        }else{
            //设置为失效
            return zzdMapper.changeZzdStatus(zzdNo);
        }
        //end  20190108 by chj
    }

    @Override
    public int createNewZzd(GfjsZzd zzdh) {
        String oldZzdNo = zzdh.getZzdNo();
        zzdh.setZzdNo(zzdhUtils.createZzdh());
        zzdh.setZzdType(Constant.ZzdType.ZY + "");
        zzdh.setStatus(Constant.ZzdStatus.UN_ACTIVE);
        zzdh.setOldZzdNo(oldZzdNo);
        return zzdMapper.insertByZzd(zzdh);
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    @Override
    public int cancelOutpatientCharge(CancelOutPatientChargeRequest request) {
        //这里是删除操作
        //删除已计算数据
        int result = receiptBalanceItemMapper.deleteByFphm(request.getZZDH() + request.getFPHM());
        //删除数据汇总
        result += receiptRollsMapper.deleteByFphm(request.getZZDH() + request.getFPHM());
        //删除转诊单汇总

        //删除数据源
        result += receiptItemMapper.deleteByFphm(request.getZZDH() + request.getFPHM());
        return result;
    }

    @Override
    public String getZzdStatus(String zzdh) {
        return zzdMapper.queryZzdStatus(zzdh);
    }

    @Override
    public List<String> queryUsedZzd(String sfzh) {
        return zzdMapper.queryUsedZzdBySfzh(sfzh);
    }

    @Override
    public GfjsZzd queryZzdIsExist(String sfzh) {
        return zzdMapper.queryZzdIsExist(sfzh);
    }

    @Override
    public GfjsZzd queryZzdIsVaild(String sfzh) {
        return zzdMapper.queryZzdIsVaild(sfzh);
    }

    @Override
    public GfjsZzd queryZyExist(String zzdh) {
        return zzdMapper.queryZyExist(zzdh);
    }

    //根据身份证号，查询未生效或者已生效的门诊转诊单
    @Override
    public GfjsZzd queryZzdByCardNo(String cardNo) {
        return zzdMapper.queryZzdByCardNo(cardNo);
    }

    //定时清理门诊转诊单
    @Override
    public void updateZzdRecord() {
       zzdMapper.handleOverTimeZzd(DateUtils.getSubDate(-7));
       zzdMapper.handleCompledZzd(DateUtils.getSubDate(-7));
    }
}
